<template>
  <div class="" style="width: 1300px; margin: auto; margin-top: 0px">
    <div style="display: flex">
      <div class="boxf">
        <span style="margin-right: 10px">Cancer Type</span>
        <el-select
          v-model="cancerType"
          placeholder="Cancer Type"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="boxf">
        <span style="margin-right: 10px">Select Method</span>
        <el-select
          @change="xios"
          v-model="method"
          placeholder="Select Method"
          style="width: 240px"
        >
          <el-option
            v-for="item in optionss"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <el-table
      v-loading="loading"
      element-loading-text="Data generation in progress..."
      height="450"
      style="width: 100%"
      empty-text="no pathway found"
      ref="multipleTableRef"
      :data="data.tableData"
      @select-all="handleSelectAll"
      @select="handleSelectionChange"
      :default-sort="{prop: 'date', order: 'descending'}"
    >
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column center prop="date" label="Cancer" /> -->
      <el-table-column center prop="pathway" label="Pathway">
        <!-- <template #default="scope">
          <ul style="padding: 2px">
            <li class="pais">sdsds</li>
            <li class="pais">sdssds</li>
            <li class="pais">sdsdsd</li>
          </ul>
        </template> -->
      </el-table-column>
      <el-table-column center prop="category" label="Category" />
      <el-table-column center prop="dataSet" label="Set/In Set" />
      <el-table-column center prop="pv" label="pValue" />
      <el-table-column center prop="fdr" label="FDR" />
      <el-table-column center prop="cancerType" label="Cancer Type" />
    </el-table>

    <div
      style="
        text-align: center;
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 10px;
      "
    >
      <el-pagination
        v-model:current-page="data.shai.pageNo"
        v-model:page-size="data.shai.pageSize"
        :page-sizes="[2, 5, 10, 20, 30, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div style="font-size: 20px; float: right">
      <a :href="`/Dynamic/${data.shai.key}.csv`" download>Download</a>
    </div>
  </div>

  <div
    style="
      position: absolute;
      bottom: 20px;
      z-index: 999999;
      left: 50%;
      transform: translateX(-50%);
    "
  >
    <el-button @click="jump" type="primary">Run scMetabolism</el-button>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick, reactive, onUpdated} from "vue";
import {useRouter, useRoute} from "vue-router";
import {useCounterStore} from "../../pina/index";
import {h} from "vue";
import {jcancerType} from "../dta/cancerTye";
import {ElNotification} from "element-plus";
import {doWork, loadResults, runJob} from "../../api/index";
const router = useRouter();
const store = useCounterStore();
const route = useRoute();
const multipleTableRef = ref(null);
let cancerValue = ref("");
let loading = ref(false);
const data = reactive({
  tableData: [],
  shai: {
    key: window.localStorage.getItem("key")
      ? window.localStorage.getItem("key")
      : "",
    pageSize: 10,
    pageNo: 1,
  },
  total: 0,
  categoryList: [],
  pathwayList: [],
  selectedItems: [],
});
const getd = async () => {
  loading.value = true;
  const paramss = new URLSearchParams();
  JSON.parse(route.query.list).forEach((item) => {
    paramss.append("effectList", item);
  });
  let aa = await doWork(paramss);
  window.localStorage.setItem("key", aa.data);
  data.shai.key = aa.data;
  if (aa.code == 200) {
    let a = await loadResults(data.shai);
    data.total = a.data.total;

    loading.value = false;
    data.tableData = a.data.dataList;
  }
  restoreSelection();
};
const handleSizeChange = () => {
  getd();
};
const handleCurrentChange = () => {
  getd();
};
const restoreSelection = () => {
  nextTick(() => {
    data.tableData.forEach((row) => {
      if (data.selectedItems.find((item) => item.pathway === row.pathway)) {
        multipleTableRef.value.toggleRowSelection(row, true);
      }
    });
  });
};

const handleSelectAll = (selection) => {
  data.selectedItems = selection;
  if (data.selectedItems.length > 15) {
    // 如果选择的数量超过4个，则取消多余的选择

    data.selectedItems.splice(15);
    multipleTableRef.value.clearSelection();
    data.selectedItems.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row, true);
    });
  }
};
const handleSelectionChange = (val, e) => {
  if (
    !data.selectedItems.some(
      (item) =>
        item.cancerType === e.cancerType &&
        item.pathway === e.pathway &&
        item.category === e.category &&
        item.dataSet === e.dataSet &&
        item.pv === e.pv &&
        item.fdr === e.fdr
    )
  ) {
    data.selectedItems.push(e);
  } else {
    data.selectedItems.pop();
  }

  if (data.selectedItems.length > 15) {
    // 如果选择的数量超过4个，则取消多余的选择
    ElNotification({
      title: "Tips",
      message: h("i", {style: "color: red"}, "Up to 15 can be selected..."),
    });
    data.selectedItems.splice(15);
    multipleTableRef.value.clearSelection();
    data.selectedItems.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row, true);
    });
  }
};
let cancerType = ref("");
let method = ref("");

const jump = () => {
  data.categoryList = [];
  data.pathwayList = [];
  data.selectedItems.forEach((item) => {
    data.categoryList.push(item.category);
    data.pathwayList.push(item.pathway);
  });
  loading.value = true;
  let a = {
    pathwayList: data.pathwayList,

    cancerType: cancerType.value,
    method: method.value,
    categoryList: data.categoryList,
    // categoryList: ["KEGG", "GO"],
  };
  runJob(a)
    .then((result) => {
      loading.value = false;

      if (result.data) {
        router.push({
          name: "analysisScM",
          query: {
            cancer: cancerType.value,
          },
        });
      } else {
        ElNotification({
          title: "Tips",
          message: h("i", {style: "color: red"}, "Generation failed..."),
        });
      }
    })
    .catch(() => {
      loading.value = false;
      ElNotification({
        title: "Tips",
        message: h("i", {style: "color: red"}, "Request timeout..."),
      });
    });
};
let options = jcancerType;

let optionss = [
  {
    value: "AUCell",
    label: "AUCell",
  },
  {
    value: "ssGSEA",
    label: "ssGSEA",
  },
  {
    value: "VISION",
    label: "VISION",
  },
];
getd();
</script>

<style scoped>
.pais {
  list-style: decimal;
}
.boxf {
  margin: 20px;
}
</style>
